package top.kaoshanji.p3ch11a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

/**
 * 代码清单-p3ch11a-215页a：多文件上传
 * @author kaoshanji
 * ^_^
 * create time 2025/4/8 20:10
 */
@WebServlet(urlPatterns = {"/multipleUploads"})
@MultipartConfig
public class MultipleUploadsServlet extends HttpServlet {

    private static final long serialVersionUID = 9991L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter writer = resp.getWriter();

        Collection<Part> parts = req.getParts(); // 可能有多个文件类型
        for (Part part: parts) {
            if (part.getContentType() != null) { // 是文件类型
                String fileName = getFileName(part);
                if (fileName != null && !fileName.isEmpty()) {
                    part.write(FileConstant.LOCAL_ROOT_PATH + fileName);

                    writer.print("<br/>Uploaded file name: " + fileName);
                    writer.print("<br/>Size: " + part.getSize());
                }
            } else { // 不是文件类型
                String partName = part.getName();
                String fieldValue = req.getParameter(partName);
                writer.print("<br/>" + partName + ": " + fieldValue);
            }
        }


    }


    /**
     * 获得文件名称
     * @param part Part
     * @return 文件名称
     */
    private String getFileName(Part part) {
        String contentDispositionHeader = part.getHeader("content-disposition");
        String[] elements = contentDispositionHeader.split(";");
        for (String element: elements) {
            if (element.trim().startsWith("filename")) {
                return element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }


}
